package siteflash.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.io.IOException;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.helper.StringHelper;
import siteflash.model.Game;
import siteflash.model.ListGame;
import siteflash.model.PageCron;
import siteflash.model.Tag;

public class CronGame extends HttpServlet {
	public static final String BUCKETNAME = "static.y1s.org";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		//Declare variable
		resp.setContentType("text/plain");
		String alias = (String) req.getParameter("alias");
		String message = "";
		PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
		Query query = psm.newQuery(ListGame.class);
		ListGame listGame = null;
		if (alias != null) {
			//Check game exits
			Key k = KeyFactory.createKey(ListGame.class.getSimpleName(), alias);
			
			try {
	        	listGame = psm.getObjectById(ListGame.class, k);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			
			message = getGame(alias);
			resp.getWriter().println(message);
			System.out.println(alias);
			
			if (listGame != null) {
				listGame.setCheckExits(true);
				psm.currentTransaction().begin();
				psm.makePersistent(listGame);
				psm.currentTransaction().commit();
			} else {
				listGame = new ListGame();
				listGame.setAlias(alias);
				listGame.setCheckExits(true);
				psm.makePersistent(listGame);
			}
			
		} else {
			query.setFilter("checkExits == false");
			query.setOrdering("alias asc");
			query.setRange(0, 1);
			List<ListGame> listResult = (List<ListGame>) query.execute();
			if (listResult.size() > 0) {
				listGame = listResult.get(0);
				alias = listGame.getAlias();
				message = getGame(alias);
				resp.getWriter().println(message);
				System.out.println(alias);
				//Update checkExists
				listGame.setCheckExits(true);
				psm.currentTransaction().begin();
				psm.makePersistent(listGame);
				psm.currentTransaction().commit();
				
			} else {
				
				System.out.println("Not game exists!");
			}
		}
	}
	
	public static String getGame(String alias) throws IOException {
		String content = "";
		String message = "";
		if (alias == null) {
			alias = "king_of_fighters_wing_1_7";
		}
		
		Game game = new Game();
		Tag tag = new Tag();
		Calendar cal = Calendar.getInstance();
		PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
		Query query = psm.newQuery(Game.class);
		query.setFilter("alias == aliasParam");
		query.declareParameters("java.lang.String aliasParam");
		query.setRange(0, 1);
		List<Game> listResult = (List<Game>) query.execute(alias);
		
		if (listResult.size() > 0) {
			message = "Game has been exits!" + alias;
		} else {
			String url = "http://www.y8.com/games/" + alias;
			content = General.getUrl(url);
			
			Document doc = Jsoup.parse(content);
			Elements tr = doc.select("#main-table").select("tbody tr");
			
			//Set alias
			game.setAlias(alias);
			
			//Set name
			String name = tr.get(0).select("td > span").first().html();
			game.setName(name);
			
			//Set played
			String strPlayed = tr.get(0).select("td > span").eq(1).html();
			int played = Integer.parseInt(strPlayed.replaceAll("[^0-9]+", ""));
			game.setPlayed(played);
			
			Elements aTags = tr.get(0).select("div#tags").select("a");
			//Set tags model
			ArrayList<String> tags = new ArrayList<String>();
			String itemTag = "";
			for (int i = 0; i < aTags.size(); i++) {
				itemTag = aTags.get(i).html();
				tags.add(itemTag);
			}
			game.setTags(tags);
			
			//Set description
			String description = tr.get(3).select("td").first().html();
			description = description.replaceAll("<strong[^>]*>(.*?)</strong>", "");
			game.setDescription(new Text(description));
			
			//Set tagSeo
			ArrayList<String> tagSeo = General.getTagSeo(description);
			game.setTagSeo(tagSeo);
			
			//Set control
			String control = tr.get(3).select("td").eq(1).html();
			control = control.replaceAll("<strong[^>]*>(.*?)</strong>", "");
			game.setControls(new Text(control));
			
			//Set Other
			Date created = (Date) cal.getTime();
			game.setCreated(created);
			game.setStatus(1);
			
			//Set image
			Elements tableImage = doc.select("table.embed-table");
			String urlString = tableImage.select("tbody tr td").first().select("img").attr("src");
			String imageName = General.getName(urlString).replaceAll("[?0-9]*$", "");
			//Get image and save to google cloud Storage
			System.out.println(urlString + " - " + imageName);
			General.getFile(urlString, imageName);
			game.setImageThumb(new Text("http://" + BUCKETNAME + "/" + imageName));
			
			//Set flash
			if (tr.get(1).select("object param").first() != null) {
				String flashString = "";
				if (tr.get(1).select("object param[name=movie]").first() != null) {
					flashString = tr.get(1).select("object param[name=movie]").first().val();
					//game.setType(new Text("flash"));
				} else {
					flashString = tr.get(1).select("object param[name=src]").first().val();
					//game.setType(new Text("shockwave"));
				}
				String flashName = General.getName(flashString).replaceAll("[?0-9]*$", "");
				int size = 0;
				//Get flash and save to google cloud storage
				size = General.getFile(flashString, flashName);
				game.setFlash(new Text("http://" + BUCKETNAME + "/" + flashName));
				game.setType(new Text("flash"));
				//Set image
				String strSize = "";
				DecimalFormat dec = new DecimalFormat("0.00");
				if((size/1000000000)>0){
					strSize = dec.format((float)size/1000000000) + " GB";
				}

				else if((size/1000000)>0){
					
					strSize = dec.format((float)size/1000000) + " MB";
				}
				else if((size/1000)>0){
					strSize = dec.format((float)size/1000) + " kB";
				}
				else{
					strSize = size + " byte";
				}
				game.setSize(new Text(strSize));
				System.out.println(game.getSize().getValue());
				
			} else if (tr.get(1).select("iframe").first() != null) {
				String flashString = tr.get(1).select("iframe").first().attr("src");
				String flashName = General.getName(flashString).replaceAll("[?cpcode=0-9]*$", "");
				System.out.println(flashString);
				int size = 0;
				//Get flash and save to google cloud storage
				size = General.getFile(flashString, flashName);
				game.setFlash(new Text("http://" + BUCKETNAME + "/" + flashName));
				game.setType(new Text("flash"));
				//Set image
				String strSize = "";
				DecimalFormat dec = new DecimalFormat("0.00");
				if((size/1000000000)>0){
					strSize = dec.format((float)size/1000000000) + " GB";
				}

				else if((size/1000000)>0){
					
					strSize = dec.format((float)size/1000000) + " MB";
				}
				else if((size/1000)>0){
					strSize = dec.format((float)size/1000) + " kB";
				}
				else{
					strSize = size + " byte";
				}
				game.setSize(new Text(strSize));
				System.out.println(game.getSize().getValue());
			} else {
				String flashString = tr.get(1).select("a[target=_blank]").select("img[class=external_game]").attr("src");
				String flashName = General.getName(flashString).replaceAll("[?0-9]*$", "");
				General.getFile(flashString, flashName);
				game.setFlash(new Text("http://" + BUCKETNAME + "/" + flashName));
				
				//Set new url
				String urlGameString = tr.get(1).select("a[target=_blank]").attr("href");
				game.setUrl(new Text(urlGameString));
				game.setType(new Text("external"));
			}
			
			//Write data to db
			psm.makePersistent(game);
			
			//Write to tags
			Query tagQuery = psm.newQuery(Tag.class);
			ArrayList<String> arrGames = null;
			List<Tag> tagResult = null;
			for (int i = 0; i < aTags.size(); i++) {
				itemTag = (String) aTags.get(i).html();
				arrGames = new ArrayList<String>();
				tagQuery = psm.newQuery(Tag.class);
				tagQuery.setFilter("name == nameParam");
				tagQuery.declareParameters("java.lang.String nameParam");
				tagQuery.setRange(0, 1);
				tagResult = (List<Tag>) tagQuery.execute(itemTag);
				if (tagResult.size() > 0 ) {
					arrGames = tagResult.get(0).getGames();
					arrGames.add(alias);
					tagResult.get(0).setGames(arrGames);
					psm.currentTransaction().begin();
					psm.makePersistent(tagResult.get(0));
					psm.currentTransaction().commit();
				} else {
					tag = new Tag();
					tag.setName(itemTag);
					arrGames.add(alias);
					tag.setGames(arrGames);
					tag.setAlias(StringHelper.replace(itemTag));
					psm.makePersistent(tag);
				}
			}
			
			message = "Add game success: " + alias;
			System.out.println("Add game success: " + alias);
		}
		
		return message;
	}
	
}
